<?php

namespace common\modules\wechat\controllers\backend;

use common\modules\wechat\models\backend\Module;
use common\modules\wechat\models\backend\ModuleSearch;
use common\modules\wechat\models\backend\ModuleForm;
use common\components\AdminController;
use common\modules\wechat\Module as WechatModule;
use Yii;
use yii\filters\VerbFilter;
use yii\web\NotFoundHttpException;
use yii\web\Response;
use yii\widgets\ActiveForm;

/**
 * 微信模块管理
 *
 * @package common\modules\wechat\controllers\backend
 */
class ModuleController extends AdminController
{

    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        $behaviors = [];

        $behaviors['verbs'] = [
            'class'   => VerbFilter::className(),
            'actions' => [
                'index'  => ['get'],
                'create' => ['get', 'post'],
                'update' => ['get', 'put', 'post'],
                'delete' => ['post', 'delete'],
            ],
        ];

        return $behaviors;
    }

    /**
     * Lists all Module models.
     *
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new ModuleSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->get());

        $page = $this->createGridViewPage($dataProvider, $searchModel);
        return $page->render();
    }

    /**
     * 安装模块
     *
     * @param $id
     * @return array|bool|string
     * @throws NotFoundHttpException
     */
    public function actionInstall($id)
    {
        $model = $this->findAvailableModule($id);
        if ( ! $model->validate())
        {
            return $this->flash(self::FLASH_MSG_TYPE_ERROR, $model->formatErrors());
        }
        if ( ! empty($_POST))
        {
            if ($model->install(false))
            {
                return $this->flash(self::FLASH_MSG_TYPE_SUCCESS, '模块安装成功!', ['index']);
            }
            elseif ( ! $model->hasErrors())
            {
                return $this->flash(self::FLASH_MSG_TYPE_ERROR, '模块安装失败!');
            }
        }
        return $this->render('install', [
            'model' => $model,
        ]);
    }

    /**
     * 卸载模块
     *
     * @param $id
     * @return array|bool|string
     * @throws NotFoundHttpException
     */
    public function actionUninstall($id)
    {
        $model = $this->findInstalledModule($id);
        if ( ! empty($_POST))
        {
            if ($model->uninstall())
            {
                return $this->flash(self::FLASH_MSG_TYPE_SUCCESS, '模块卸载成功!', ['index']);
            }
            else
            {
                return $this->flash(self::FLASH_MSG_TYPE_ERROR, '模块卸载失败!');
            }
        }
        return $this->render('uninstall', [
            'model' => $model,
        ]);
    }

    /**
     * Creates a new Module model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     *
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new ModuleForm(['scenario' => ModuleForm::SCENARIO_CREATE]);

        $model->isNewRecord = true;

        if ($model->load(Yii::$app->request->post()))
        {
            if (Yii::$app->request->isAjax)
            {
                Yii::$app->response->format = Response::FORMAT_JSON;
                return ActiveForm::validate($model);
            }
            else
            {
                if ($model->save())
                {
                    Yii::$app->session->setFlash(self::FLASH_MSG_TYPE_SUCCESS, '创建成功!');
                    return $this->redirect(['update', 'id' => $model->id]);
                }
                else
                {
                    Yii::$app->session->setFlash(self::FLASH_MSG_TYPE_ERROR, $model->formatErrors());
                    return $this->refresh();
                }
            }
        }

        $page = $this->createFormViewPage(
            $model,
            ModuleForm::SCENARIO_CREATE,
            [
                'pageTitle' => 'Update',
            ]
        );
        return $page->render();
    }

    /**
     * Updates an existing Module model.
     * If update is successful, the browser will be redirected to the 'view' page.
     *
     * @param string $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);
        $model->setScenario(ModuleForm::SCENARIO_UPDATE);

        if ($model->load(Yii::$app->request->post()))
        {
            if (Yii::$app->request->isAjax)
            {
                Yii::$app->response->format = Response::FORMAT_JSON;
                return ActiveForm::validate($model);
            }
            else
            {
                if ($model->save())
                {
                    Yii::$app->session->setFlash(self::FLASH_MSG_TYPE_SUCCESS, '更新成功!');
                }
                else
                {
                    Yii::$app->session->setFlash(self::FLASH_MSG_TYPE_ERROR, $model->formatErrors());
                    return $this->refresh();
                }
            }
        }

        $page = $this->createFormViewPage(
            $model,
            ModuleForm::SCENARIO_UPDATE,
            [
                'pageTitle' => 'Update',
            ]
        );
        return $page->render();
    }

    /**
     * Deletes an existing Module model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     *
     * @param string $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the Module model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     *
     * @param string $id
     * @return Module the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = ModuleForm::findOne($id)) !== null)
        {
            return $model;
        }
        else
        {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }

    /**
     * 查找可用的扩展模块
     *
     * @param $id
     * @return Module
     * @throws NotFoundHttpException
     */
    public function findAvailableModule($id)
    {
        if (($model = WechatModule::findAvailableModuleById($id)) !== null)
        {
            return $model;
        }
        else
        {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }

    /**
     * 查找已安装的模块
     *
     * @param $id
     * @return Module
     * @throws NotFoundHttpException
     */
    public function findInstalledModule($id)
    {
        if (($model = Module::findOne($id)) !== null)
        {
            return $model;
        }
        else
        {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}
